package br.com.sig.security;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

import org.jboss.seam.security.permission.PermissionResolver;

import br.com.sig.BaseException;
import br.com.sig.security.business.model.entity.Permission;
import br.com.sig.security.business.model.entity.Role;
import br.com.sig.security.business.model.entity.User;

@Named
@SessionScoped
public class BasePermissionResolver implements Serializable, PermissionResolver {
	
	private static final long serialVersionUID = 5765740491142798609L;
	
	private Map<String, Permission> permissions = new HashMap<String, Permission>();

	@Override
	public boolean hasPermission(Object permission, String action) {
		if (permission != null || action != null) {
			return permissions.containsKey(permission + "." + action)
					|| permissions.containsKey(permission);
		}
		return false;
	}

	@Override
	public void filterSetByAction(Set<Object> resources, String permission) {
	}
	
	/**
	 * Load the permissions that are associated with the roles of the user.
	 * 
	 * @param user
	 * @throws BaseException
	 */
	public void loadPermissions(User user) throws BaseException {
		this.permissions.clear();
		List<Role> roles = user.getRoles();
		List<Permission> permissions = null;
		for (Role role : roles) {
			permissions = role.getPermissions();
			if (permissions != null) {
				for (Permission permission : permissions) {
					this.permissions.put(permission.getCode(), permission);
				}				
			}
		}
	}

}
